import datetime

from fastapi import APIRouter, Depends, Body
import motor.motor_asyncio
from utils import update_settings
from dependencies import get_mongo_settings_coll
from schema.req.business_safety_settings import InterfaceStatisticSettings, LogFilePathSettings, InterfaceCallFreqSettings
from schema.resp.business_safety_settings import ApiRecord
from schema.resp import RestfulModel
import pandas as pd
from typing import List
from datetime import datetime


AsyncIOMotorCollection = motor.motor_asyncio.AsyncIOMotorCollection


business_safety_settings_router = APIRouter(prefix='/business-safety/setting', tags=['业务安全感知-配置项'])


class SettingsName:
    INTERFACE_STATISTIC = 'business_safety_interface_statistic'
    LOG_FILE = 'log-file'
    INTERFACE_CALL_FREQ = 'business_safety_interface_call_freq_statistic'
    KEY_BUSINESS_STATISTIC = 'business_safety_key_business_statistic'


success_resp = RestfulModel.success(None)


@business_safety_settings_router.post('/interface-statistic',
                                      response_model=RestfulModel,
                                      summary='修改业务数据统计的配置')
async def modify_interface_statistic_settings(settings: InterfaceStatisticSettings = Body(...),
                                              coll: AsyncIOMotorCollection = Depends(get_mongo_settings_coll)):
    await update_settings(coll, SettingsName.INTERFACE_STATISTIC, settings.dict())
    return success_resp


@business_safety_settings_router.post('/log-file-path',
                                      response_model=RestfulModel,
                                      summary='修改日志文件的路径')
async def modify_log_file_path(file_path: LogFilePathSettings = Body(...),
                               coll: AsyncIOMotorCollection = Depends(get_mongo_settings_coll)):
    await update_settings(coll, SettingsName.LOG_FILE, file_path.path)
    return success_resp


@business_safety_settings_router.post('/interface-freq',
                                      response_model=RestfulModel,
                                      summary='修改接口调用频率统计的配置')
async def modify_interface_call_freq_settings(settings: InterfaceCallFreqSettings,
                                              coll: AsyncIOMotorCollection = Depends(get_mongo_settings_coll)):
    dt_list = pd.date_range(settings.start_time, settings.end_time, periods=settings.periods + 1)
    time_range = [
        (dt_list[i], dt_list[i + 1])
        for i in range(len(dt_list) - 1)
    ]
    await update_settings(coll, SettingsName.INTERFACE_CALL_FREQ, {'time_range': time_range})
    return success_resp


@business_safety_settings_router.delete('/key-business',
                                        response_model=RestfulModel,
                                        summary='删除所要监控的一个 API')
async def delete_one_api(api: str = Body(..., embed=True),
                         coll: AsyncIOMotorCollection = Depends(get_mongo_settings_coll)):
    await coll.update_one({'name': SettingsName.KEY_BUSINESS_STATISTIC}, {'$pull': {'data.api_list': {'api': api}}})
    return success_resp


@business_safety_settings_router.get('/key-business',
                                     # response_model=RestfulModel[List[ApiRecord]],
                                     summary='获取目前的 API 列表')
async def get_api_list(coll: AsyncIOMotorCollection = Depends(get_mongo_settings_coll)):
    doc = await coll.find_one({'name': SettingsName.KEY_BUSINESS_STATISTIC})
    api_list = doc['data']['api_list']
    print(api_list)
    return RestfulModel.success(api_list)


@business_safety_settings_router.put('/key-business',
                                     response_model=RestfulModel,
                                     summary='新增一条监控的 api')
async def add_api(api: str = Body(..., embed=True),
                  coll: AsyncIOMotorCollection = Depends(get_mongo_settings_coll)):
    record = ApiRecord(api=api, create_time=datetime.now())
    await coll.update_one({'name': SettingsName.KEY_BUSINESS_STATISTIC}, {'$addToSet': {'data.api_list': record.dict()}})
    return success_resp
